package io.renren.modules.admin.service.impl;

import io.renren.modules.admin.controller.PhoneController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.admin.dao.ManagerWorkDao;
import io.renren.modules.admin.entity.ManagerWorkEntity;
import io.renren.modules.admin.service.ManagerWorkService;


@Service("managerWorkService")
public class ManagerWorkServiceImpl extends ServiceImpl<ManagerWorkDao, ManagerWorkEntity> implements ManagerWorkService {

    @Autowired
    private PhoneController phoneController;
    @Autowired
    private ManagerWorkDao managerWorkDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long userId) {
        IPage<ManagerWorkEntity> page = this.page(
                new Query<ManagerWorkEntity>().getPage(params),
                new QueryWrapper<ManagerWorkEntity>().orderByDesc("create_time").eq("user_id",userId)
        );
        List<ManagerWorkEntity> managerWorkEntities = page.getRecords();
        StringBuffer sb = new StringBuffer();
        managerWorkEntities.forEach(managerWorkEntity -> {
            String phoneIds = managerWorkEntity.getPhoneIds();
            if (phoneIds != null) {
                String[] split = phoneIds.trim().split(",");
                for (String s : split) {
                    if (s != null && s != ""){
                        String aliasById = phoneController.getAliasById(s,userId);
                        if (aliasById != "") {
                            sb.append(aliasById+",");
                        }
                    }
                }
                if (StringUtils.equals(sb.toString(),"")) {
                    managerWorkEntity.setAlias("");
                }else {
//                    System.out.println("sb.toString() = " + sb.toString());
                    String s = sb.deleteCharAt(sb.length() - 1).toString();
                    managerWorkEntity.setAlias(s);
                }
            }else managerWorkEntity.setAlias("");
            sb.delete(0, sb.length());
        });
        page.setRecords(managerWorkEntities);
        return new PageUtils(page);
    }

    @Override
    public String queryNameByDeviceId(String deviceId) {
        List<String> names  = this.managerWorkDao.selectName(deviceId);
        String name = "";
        if (names != null && names.size() >= 1) {
            name = names.get(0);// 最近创建的为准
        } else return null;
        String workName = name;
        if (workName == "") {
            return null;
        }
        return workName;

    }

}